<template>
  <div class="fab-container">
    <!-- 控制面板 - 左上角 -->
    <h1>FAB CleanRoom 热力溯源</h1>
    <div class="control-panel">
      <div class="control-group">
        <span class="control-label">视图模式:</span>
        <px-button-group>
          <px-button :type="currentView === 'temperature' ? 'primary' : ''" size="small" @click="toggleView('temperature')">
            <px-icon><Sunny /></px-icon>
            <span>温度</span>
          </px-button>
          <!-- <px-button :type="currentView === 'humidity' ? 'primary' : ''" size="small" @click="toggleView('humidity')">
            <px-icon><Watermelon /></px-icon>
            <span>湿度</span>
          </px-button> -->
        </px-button-group>
      </div>

      <div class="control-group">
        <span class="control-label">时间模式:</span>
        <px-select v-model="timeMode" size="small" style="width: 120px" @change="switchTimeMode">
          <px-option label="实时监控" value="realtime" />
          <px-option label="历史查询" value="history" />
        </px-select>

        <px-date-picker
          v-if="!isRealtime"
          v-model="historyDateTime"
          :defaultTime="defaultTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择日期时间"
          size="small"
          style="width: 200px; margin-left: 10px"
          @change="updateHistoryData"
        />
      </div>

      <div class="status-info">
        <px-icon :class="['status-icon', refreshStatus]">
          <Loading v-if="isRefreshing" />
          <SuccessFilled v-else />
        </px-icon>
        <span>最后更新: {{ lastUpdateTime }}</span>
        <span v-if="isRealtime" class="refresh-countdown">({{ countdown }}秒后刷新)</span>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="fab-content">
      <StatsPanel v-if="isRealtime" :areas="areas" :current-view="currentView" :last-update-time="lastUpdateTime" />

      <div class="fab-map">
        <img :src="proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom/洁净室-2.5d.jpg`)" class="fab-image" alt="FAB 3F平面图" />
        <HeatmapChart ref="heatmapChart" :areas="areas" :current-view="currentView" @area-click="showSpcModal" />
      </div>
    </div>

    <SpcModal v-if="showModal" :area="selectedArea" :current-view="currentView" @area-change="handleAreaChange" @close="closeSpcModal" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onBeforeUnmount, getCurrentInstance } from "vue";
// import { Sunny, Watermelon, Loading, SuccessFilled } from "@element-plus/icons-vue";
import { useFabStore } from "@/store/modules/fabStore";
import HeatmapChart from "./HeatmapChart.vue";
import StatsPanel from "./StatsPanel.vue";
import SpcModal from "./SpcModal.vue";
import { fetchRealtimeData, fetchHistoryData } from "../utils/api";

const { proxy }: any = getCurrentInstance();

const fabStore = useFabStore();
const areas = computed(() => fabStore.areas);

// 视图控制
const currentView = ref<"temperature" | "humidity">("temperature");
const timeMode = ref<"realtime" | "history">("realtime");
const isRealtime = computed(() => timeMode.value === "realtime");
const lastUpdateTime = ref("");
const defaultTime = new Date(2000, 1, 1, 1, 1, 1);
const historyDateTime = ref<Date>(proxy.parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"));

// 刷新状态
const isRefreshing = ref(false);
const countdown = ref(10);
const refreshStatus = computed(() => (isRefreshing.value ? "status-loading" : "status-success"));

// 模态框控制
const showModal = ref(false);
const selectedArea = ref<any>(null);
const heatmapChart = ref<any>(null);

let updateInterval: ReturnType<typeof setInterval> | null = null;
let countdownInterval: ReturnType<typeof setInterval> | null = null;

// 初始化数据 - 修改后的部分
onMounted(() => {
  // 初始加载数据
  updateRealtimeData();

  // 监听实时模式变化
  watch(
    isRealtime,
    newVal => {
      if (newVal) {
        startRealtimeUpdate();
        startCountdown();
      } else {
        stopRealtimeUpdate();
        stopCountdown();
      }
    },
    { immediate: true }
  );
});

onBeforeUnmount(() => {
  stopRealtimeUpdate();
  stopCountdown();
});

// 视图切换
const toggleView = (type: "temperature" | "humidity") => {
  currentView.value = type;
  heatmapChart.value?.updateChart();
};

// 时间模式切换
const switchTimeMode = () => {
  // 不再需要额外处理，因为watch已经监听isRealtime变化
};

// 实时数据更新 - 修改后的部分
const startRealtimeUpdate = () => {
  // 先停止已有定时器
  stopRealtimeUpdate();

  // 立即执行一次更新
  updateRealtimeData();

  // 启动新定时器
  updateInterval = setInterval(() => {
    updateRealtimeData();
  }, 10000); // 10秒刷新一次
};

const updateRealtimeData = async () => {
  isRefreshing.value = true;
  try {
    const data = await fetchRealtimeData();
    fabStore.updateAreas(data);
    lastUpdateTime.value = new Date().toLocaleString();
    resetCountdown();
  } catch (error) {
    console.error("数据更新失败:", error);
  } finally {
    isRefreshing.value = false;
  }
};

const stopRealtimeUpdate = () => {
  if (updateInterval) {
    clearInterval(updateInterval);
    updateInterval = null;
  }
};

// 倒计时控制 - 修改后的部分
const startCountdown = () => {
  stopCountdown();
  countdown.value = 10;
  countdownInterval = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      resetCountdown();
    }
  }, 1000);
};

const resetCountdown = () => {
  stopCountdown();
  countdown.value = 10;
  if (isRealtime.value) {
    startCountdown();
  }
};

const stopCountdown = () => {
  if (countdownInterval) {
    clearInterval(countdownInterval);
    countdownInterval = null;
  }
};

// 历史数据更新
const updateHistoryData = async () => {
  if (!historyDateTime.value) return;

  const data = await fetchHistoryData(historyDateTime.value);
  fabStore.updateAreas(data);
  lastUpdateTime.value = historyDateTime.value.toLocaleString();
};

// 切换区域
const handleAreaChange = (area: any) => {
  console.log(area, "选中的区域");
  selectedArea.value = area;
};

// SPC模态框控制
const showSpcModal = (area: any) => {
  selectedArea.value = area;
  // showModal.value = true;
};

const closeSpcModal = () => {
  showModal.value = false;
};
</script>

<style scoped lang="scss">
.fab-container {
  position: relative;
  width: 100%;
  height: calc(100vh - 126px);
  overflow: hidden;
  background-color: #f5f7fa;
}

h1 {
  margin: 5px 0;
  font-size: 20px;
  text-align: center;
}

.control-panel {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 10;
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-width: 400px;
  padding: 12px 16px;
  background-color: rgb(255 255 255 / 95%);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgb(0 0 0 / 10%);

  .control-group {
    display: flex;
    gap: 10px;
    align-items: center;

    .control-label {
      font-size: 14px;
      font-weight: 500;
      color: #606266;
    }
  }

  .status-info {
    display: flex;
    gap: 8px;
    align-items: center;
    font-size: 13px;
    color: #606266;

    .status-icon {
      font-size: 16px;

      &.status-loading {
        color: #409eff;
        animation: spin 1s linear infinite;
      }

      &.status-success {
        color: #67c23a;
      }
    }

    .refresh-countdown {
      color: #909399;
    }
  }
}

.fab-content {
  position: relative;
  width: 100%;
  height: 100%;
  padding-top: 20px;
}

.fab-map {
  position: relative;
  width: 100%;
  height: 100%;

  .fab-image {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>
